package com.zhiqingchun.web.user;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhiqingchun.dao.account.IUserDao;
import com.zhiqingchun.dao.account.UserResult;
import com.zhiqingchun.pojo.Usr;

@Controller
@RequestMapping("/userInfo.html")
public class UserInfoController {

	@RequestMapping(method = RequestMethod.GET)
	public String get(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		Usr usr = (Usr) request.getSession().getAttribute("user");
		UserResult userResult = userDao.byId(usr.getId());
		if (userResult.isSuccess()) {
			map.addAttribute("userInfo", userResult.getUsr());
		}
		return "user/userInfo";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String post(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8") ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Usr usr = (Usr) request.getSession().getAttribute("user");
		try {
			String _usr = ServletRequestUtils.getStringParameter(request, "usr");
			String avatar = ServletRequestUtils.getStringParameter(request, "avatar");
			String intro = ServletRequestUtils.getStringParameter(request, "intro");
			int city = ServletRequestUtils.getIntParameter(request, "city");
			usr.setUsr(_usr);
			usr.setAvatar(avatar);
			usr.setIntro(intro);
			usr.setCity(city);
		} catch (ServletRequestBindingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		userDao.update(usr);
		return "redirect:user.html?id=" + usr.getId();
	}
	
	@Autowired
	private IUserDao userDao;

	public IUserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}
	
}
